package handler

import (
	"encoding/json"
	"exam-11-assistant/cache"
	"exam-11-assistant/model"
	"github.com/gin-gonic/gin"
	"time"
)

func Add(c *gin.Context) {

	name := c.PostForm("name")
	content := c.PostForm("content")

	for name == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段为空",
		})
		return
	}

	data := model.Shop{
		Name:    name,
		Content: content,
	}
	err := model.DB.Create(&data).Debug().Error

	var shop model.Shop
	redis_key := "shop_add_"
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		model.DB.Create(&data).Debug()
		json.Marshal(&shop)
		cache.Rdb.Set(cache.Ctx, redisData, redisData, time.Hour*2).Result()
	}

	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {

	var shop []model.Shop
	model.DB.Model(model.Shop{}).Find(&shop)

	var shops model.Shop
	redis_key := "shop_add_"
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		model.DB.Model(model.Shop{}).Find(&shop)
		json.Marshal(&shops)
		cache.Rdb.Set(cache.Ctx, redisData, redisData, time.Hour*2).Result()
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": shop,
	})
	return

}
